package com.tsinghua.server.config.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Map;

public class JWTUtils {
    private static final String SECRET = "be8fbf50764e9c82212bcebb9819f698";

    /**
     * 生成token header.payload.sing
     * @param map
     * @param expired
     * @return
     */
    public static String getToken(Map<String,String> map, Integer expired){
        Calendar instance = Calendar.getInstance();
        //设置过期时间单位:秒
        instance.add(Calendar.SECOND,expired);
        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        //payload
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        //制定令牌过期时间
        String token = builder.withExpiresAt(instance.getTime())
                //sign
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    /**
     * 验证token 合法性 || 获取token信息方法
     * @param token
     */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }

    /**
     * 获取token信息方法
     * @param token
     */
    public static DecodedJWT getTokenInfo(String token) {
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return verify;
    }

    /**
     * 从token中取出user name
     * @param request header
     * @return userName
     */
    public static String getUserName(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        DecodedJWT verify = getTokenInfo(token);
        return verify.getClaim("userName").asString();
    }


    /**
     * 获取当前用户userId
     * @param request
     * @return
     */
    public static Long getUserId(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        DecodedJWT verify = getTokenInfo(token);
        return Long.valueOf(verify.getClaim("userId").asString());
    }

}
